package com.tencent.sr.iris.activity.common.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.tencent.sr.iris.activity.common.config.ScrmServerConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

@Slf4j
@Component
public class ScrmServerHttpUtil {

    @Autowired
    private ScrmServerConfig scrmServerConfig;

    public static final int ONE = 1;
    public static final int ZERO = 0;

    /**
     * 处理形如：{data:{mapping:[]}}
     *
     * @param path
     * @param mapping 映射路径
     * @param reqBody
     * @param tClass
     * @param <T>
     * @return
     */
    public <T> List<T> postCommonListZeroForMapping(String path, String mapping, String reqBody, Class<T> tClass) {
        JSONObject jsonRes = postCommonZero(path, reqBody);
        JSONArray jsonData = jsonRes.getJSONObject("data").getJSONArray(mapping);
        return JSON.parseArray(jsonData.toJSONString(), tClass);
    }

    public <T> T postCommonOne(String path, String reqBody, Class<T> tClass) {
        JSONObject jsonRes = postCommonOne(path, reqBody);
        JSONObject jsonData = jsonRes.getJSONObject("data");
        return JSON.parseObject(jsonData.toJSONString(), tClass);
    }

    public void postCommonOneNoResult(String path, String reqBody) {
        JSONObject jsonRes = postCommonOne(path, reqBody);
        log.info("scrm.postObjectNoResult: path:{}、req:{}、response:{}", path, reqBody, jsonRes);
    }

    /**
     * 成功响应码为0的场景
     *
     * @param path 请求路径
     * @param reqBody 请求响应体
     * @return
     */
    private JSONObject postCommonZero(String path, String reqBody) {
        return OkHttpClient.postCommon(scrmServerConfig.getUrl(), scrmServerConfig.getApiAppKey(),
                scrmServerConfig.getApiAppSecret(), path, reqBody, ZERO);
    }

    /**
     * 成功响应码为1的场景
     *
     * @param path 请求路径
     * @param reqBody 请求响应体
     * @return
     */
    private JSONObject postCommonOne(String path, String reqBody) {
        return OkHttpClient.postCommon(scrmServerConfig.getUrl(), scrmServerConfig.getApiAppKey(),
                scrmServerConfig.getApiAppSecret(), path, reqBody, ONE);
    }
}
